package w.z.x.framework.repository.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 读写分离配置
 *
 * @author 魏祖潇
 */
@Slf4j
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate")
public class JdbcTemplateConfig implements Ordered {

    @Primary
    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @ConditionalOnProperty("spring.datasource.slave.url")
    @Bean
    public JdbcTemplate slaveJdbcTemplate(@Qualifier("slaveDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @ConditionalOnMissingBean(name = "slaveJdbcTemplate")
    @Bean(name = "slaveJdbcTemplate")
    public JdbcTemplate slaveJdbcTemplateMissing(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
